package com.adtech.adms.commons.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.adtech.adms.system.pojo.User;
import com.adtech.core.Settings;
import com.adtech.core.util.ExcelUtil;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
  
/**
 * 
 * 将office导出html工具
 * @author Dormin 
 * @since 2012-2-1 
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class OfficeUtil {   
 
	private static final Logger log = Logger.getLogger(OfficeUtil.class);
    /**  
     * PowerPoint转成HTML  
     *   
     * @param pptPath  
     *            PowerPoint文件全路径  
     * @param htmlfile  
     *            转换后HTML存放路径  
     */  
    public static Boolean pptToHtmlOld(String pptPath, String htmlPath) {  
        Boolean b = false;   
        ActiveXComponent offCom = new ActiveXComponent("PowerPoint.Application");   
        try {   
            offCom.setProperty("Visible", new Variant(true));   
            Dispatch excels = offCom.getProperty("Presentations").toDispatch();   
            Dispatch excel = Dispatch.invoke(   
                    excels,   
                    "Open",   
                    Dispatch.Method,   
                    new Object[] { pptPath, new Variant(false),   
                            new Variant(false) }, new int[1]).toDispatch();   
            Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {   
                    htmlPath, new Variant() }, new int[1]);   
            new Variant(false);   
            Dispatch.call(excel, "Close");   
            b=true;   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
            offCom.invoke("Quit", new Variant[] {});   
            ComThread.Release();   
        }   
        return b;
    }   
    
    public static Boolean pptToHtml(String pptPath, String htmlPath) {  
    	ComThread.InitSTA();  
        ActiveXComponent activexcomponent = new ActiveXComponent(  
                "PowerPoint.Application");  
        boolean flag = false;  
        try {  
            Dispatch dispatch = activexcomponent.getProperty("Presentations")  
                    .toDispatch();
            Dispatch dispatch1 = Dispatch.call(dispatch, "Open", pptPath,  
                    new Variant(-1), new Variant(-1), new Variant(0))  
                    .toDispatch();  
            Dispatch.call(dispatch1, "SaveAs", htmlPath, new Variant(12));  
            Variant variant = new Variant(-1);  
            Dispatch.call(dispatch1, "Close");  
            flag = true;  
        } catch (Exception exception) {  
            System.out.println("|||" + exception.toString());  
        } finally {  
            activexcomponent.invoke("Quit", new Variant[0]);  
            ComThread.Release();  
            ComThread.quitMainSTA();  
        }  
        return flag;  
    }   
  
    /**  
     * WORD转成HTML  
     *   
     * @param wordPath  
     *            WORD文件全路径  
     * @param htmlPath  
     *            生成的HTML存放路径  
     */  
    public static Boolean wordToHtml(String wordPath, String htmlPath) {   
        Boolean b = false;   
        ActiveXComponent offCom = new ActiveXComponent("Word.Application");   
        try {   
            offCom.setProperty("Visible", new Variant(false));   
            Dispatch wordDis = offCom.getProperty("Documents").toDispatch();   
            Dispatch doc = Dispatch.invoke(   
                    wordDis,   
                    "Open",   
                    Dispatch.Method,   
                    new Object[] { wordPath, new Variant(true),   
                            new Variant(true) }, new int[1]).toDispatch();   
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {   
                    htmlPath, new Variant(8) }, new int[1]);   
            Variant f = new Variant(false);   
            Dispatch.call(doc, "Close", f);   
            b=true;   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
            offCom.invoke("Quit", new Variant[] {});   
        }   
        return b;   
    }   
  
    /**  
     * EXCEL转成HTML  
     *   
     * @param xlsfile  
     *            EXCEL文件全路径  
     * @param htmlfile  
     *            转换后HTML存放路径  
     */  
    public static Boolean excelToHtml(String excelPath, String htmlPath) {   
        Boolean b = false;   
        ActiveXComponent offCom = new ActiveXComponent("Excel.Application");   
        try {   
            offCom.setProperty("Visible", new Variant(false));   
            Dispatch excels = offCom.getProperty("Workbooks").toDispatch();   
            Dispatch excel = Dispatch.invoke(   
                    excels,   
                    "Open",   
                    Dispatch.Method,   
                    new Object[] { excelPath, new Variant(false),   
                            new Variant(true) }, new int[1]).toDispatch();   
            Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {   
                    htmlPath, new Variant(44) }, new int[1]);   
            Variant f = new Variant(false);   
            Dispatch.call(excel, "Close", f);   
            b=true;   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
            offCom.invoke("Quit", new Variant[] {});   
            ComThread.Release();   
        }   
        return b;   
    }   
    
    /**  
     * EXCEL07格式转03格式
     *   
     * @param xlsfile  
     *            EXCEL文件全路径  
     * @param htmlfile  
     *            转换后EXCEL存放路径  
     */  
    public static Boolean xlsxToxls(String origExcelPath, String destExcelPath) {   
        Boolean b = false;   
        ActiveXComponent objExcel = new ActiveXComponent("Excel.Application");   
        try {   
        	Dispatch.put(objExcel.getObject(), "DisplayAlerts", new Variant(false));
        	Dispatch.put(objExcel.getObject(), "Visible", new Variant(false));
        	Dispatch autoRecover = objExcel.getProperty("AutoRecover").toDispatch();
        	Dispatch.put(autoRecover, "Enabled", new Variant(true));
        	Dispatch workbook = objExcel.getProperty("Workbooks").toDispatch();
        	workbook = Dispatch.call(workbook, "Open", origExcelPath).toDispatch();
        	Dispatch oExcel = Dispatch.call(objExcel, "Workbooks").getDispatch();
        	Dispatch.call(workbook, "SaveAs", destExcelPath, new Variant(-4143));
            b=true;   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
        	objExcel.invoke("Quit", new Variant[] {});   
            ComThread.Release();   
        }   
        return b;   
    }
    
    /**  
     * EXCEL03格式转07格式 
     *   
     * @param xlsfile  
     *            EXCEL文件全路径  
     * @param htmlfile  
     *            转换后EXCEL存放路径  
     */  
    public static Boolean xlsToxlsx(String origExcelPath, String destExcelPath) {   
        Boolean b = false;   
        ActiveXComponent objExcel = new ActiveXComponent("Excel.Application");   
        try {   
        	Dispatch.put(objExcel.getObject(), "DisplayAlerts", new Variant(false));
        	Dispatch.put(objExcel.getObject(), "Visible", new Variant(false));
        	Dispatch autoRecover = objExcel.getProperty("AutoRecover").toDispatch();
        	Dispatch.put(autoRecover, "Enabled", new Variant(true));
        	Dispatch workbook = objExcel.getProperty("Workbooks").toDispatch();
        	workbook = Dispatch.call(workbook, "Open", origExcelPath).toDispatch();
        	Dispatch oExcel = Dispatch.call(objExcel, "Workbooks").getDispatch();
        	Dispatch.call(workbook, "SaveAs", destExcelPath, new Variant(51));
            b=true;   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
        	objExcel.invoke("Quit", new Variant[] {});   
            ComThread.Release();   
        }   
        return b;   
    }
    
    /**
	 * 根据模板文件获取Workbook（强制将03格式转换为07格式）
	 * @param filePath
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @author Dormin
	 */
	public static Workbook getWorkbook(String filePath,User user) throws FileNotFoundException,IOException {
		if(filePath.endsWith(".xls")) {
			String folder = (Settings.get(Settings.TMPDIR_PATH)+File.separator+user.getLoginName()+File.separator).replace("/", "\\");
			String newFilePath = folder + System.currentTimeMillis()+".xlsx";
			try {
				xlsToxlsx(filePath.replace("/", "\\"), newFilePath);
				File newFile = new File(newFilePath);
				if(newFile.exists()) {
					Workbook wb = ExcelUtil.getWorkbook(newFilePath);
					return wb;
				}
			} catch(Exception e) {
				log.error("ConfigExportServiceImpl.getWorkbook() call jacob failed:"+e.getMessage());
			} finally {
				File newFile = new File(newFilePath);
				if(newFile.exists()) {
					newFile.delete();
				}
			}
		}
		return ExcelUtil.getWorkbook(filePath);
	}
	
	/**
	 * 写入excel文件(将07格式转换为03格式)
	 * @param book
	 * @param filename
	 * @param user
	 * @throws IOException
	 * @author Dormin
	 */
	public static void write(Workbook book, String filename,User user) throws IOException {
		if(filename.endsWith(".xls") && book instanceof XSSFWorkbook) {
			String folder = (Settings.get(Settings.TMPDIR_PATH)+File.separator+user.getLoginName()+File.separator).replace("/", "\\");
			String newFilePath = folder + System.currentTimeMillis()+".xlsx";
			ExcelUtil.write(book, newFilePath);
			try{
				xlsxToxls(newFilePath,filename.replace("/", "\\"));
				
			} catch(Exception e){
				log.error("OfficeUtil.write() call jacob failed:"+e.getMessage());
			} finally {
				File newFile = new File(newFilePath);
				if(newFile.exists()) {
					newFile.delete();
				}
			}
			return;
		}
		ExcelUtil.write(book, filename);
	}
  
    public static void main(String[] args) {
    	/*
    	xlsToXlsx("D:\\temp\\preplan.xls","D:\\temp\\preplan.xlsx");  
    	File file = new File("D:\\temp\\preplan.xlsx");
		try {
			Workbook wb = ExcelUtil.getWorkbook(file.getPath());
			//WorkBookHelper wbHelper = new WorkBookHelper(wb);
			CellStyle style = wb.createCellStyle();
			Sheet sheet = wb.getSheetAt(0);
            Row row = sheet.getRow(0);
            Cell cell = row.getCell(0);
            System.out.println(cell.getStringCellValue());
			ExcelUtil.write(wb, "D:\\temp\\preplan-1.xlsx");
			File newFile = new File("D:\\temp\\preplan-1.xlsx");
			xlsxToXls("D:\\temp\\preplan-1.xlsx","D:\\temp\\preplan-1.xls");
			if(file.exists()) {
				file.delete();
			}
			if(newFile.exists()) {
				newFile.delete();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}*/

    }   
}  
